package com.yanze.schoolinformation.model.http;

import com.google.gson.JsonParseException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;

import org.json.JSONException;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

/**
 * Created by MrZheng on 2018/4/9.
 */

public abstract class DeforSubscriber<T> implements Subscriber<T> {
    private Subscription mSubscription;

    @Override
    public void onSubscribe(Subscription s) {
        this.mSubscription = s;
        s.request(Integer.MAX_VALUE);
    }

    @Override
    public void onNext(T t) {
        _onNext(t);
    }

    @Override
    public void onError(Throwable e) {
        String errorMessage;
        if (e instanceof HttpException) {     //   HTTP错误
            errorMessage = "HTTP错误";
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {   //   连接错误
            errorMessage = "网络错误";
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            errorMessage = "链接超时";
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {   //  解析错误
            errorMessage = "解析错误";
        } else {
            errorMessage = "未知错误";
        }
        _onError(errorMessage);
        if (mSubscription != null) {
            mSubscription.cancel();
        }
    }

    @Override
    public void onComplete() {
        _onComplete();
        if (mSubscription != null) {
            mSubscription.cancel();
        }
    }

    public abstract void _onSubscribe(Subscription s);

    public abstract void _onNext(T t);

    public abstract void _onError(String errmsg);

    public void _onComplete(){}
}
